<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Db;
class Doctor extends Controller{
    public function Add(){
        if (session("login")!=1) return $this->error("请先登录");
        if (session("type")!="admin") return $this->error("无权访问");
        
        if (isset($_POST["add"])) {
            if(!isset($_POST["clinic"])) $_POST["clinic"]=session('cid');
            $rows=db('doctor')->insert(["name"=>$_POST["name"],"phone"=>$_POST["phone"],"passwd"=>md5($_POST["passwd"]),"clinic"=>$_POST["clinic"]]);
            if ($rows==1) $this->success('新增成功','/Doctor/List');
            else $this->error('新增失败');
        }else {
            $res=db('clinic')->select();
            $this->assign("arr",$res);
            return $this->fetch("add");
        }
    }
    public function List(){
        if (session("login")!=1) return $this->error("请先登录");
        if (session("type")!="admin") return $this->error("无权访问");
        if (session("cid")==0)
            $result=Db::query("SELECT doctor.id,doctor.name,doctor.phone,clinic.name AS cname FROM doctor,clinic WHERE clinic.id = doctor.clinic");
        else
            $result=db("doctor")->where("clinic",session("cid"))->select();
        $this->assign("arr",$result);
        return $this->fetch("list");
    }
    public function Edit(){
        if (session("login")!=1) return $this->error("请先登录");
        if (session("type")!="admin") return $this->error("无权访问");
        $res=db("doctor")->where("id",input("id"))->find();
        if (isset($_POST["edit"])) {        
            if($_POST['passwd']!=$res["passwd"]) $_POST["passwd"]=md5($_POST["passwd"]);
            if (session("cid")=="0")
            $resa=db("doctor")->where("id",input("id"))->update(["name"=>$_POST["name"],"passwd"=>$_POST["passwd"],"phone"=>$_POST["phone"]]);
            else $resa=db("doctor")->where("id",input("id"))->where("clinic",session("cid"))->update(["name"=>$_POST["name"],"passwd"=>$_POST["passwd"],"phone"=>$_POST["phone"]]);
            if (($resa==1)) $this->success('更新成功','/Doctor/List');
            else $this->error('更新失败');
        }else{
            return view('edit',$res);
        }
    }
    public function Del(){
        if (session("login")!=1) return $this->error("请先登录");
        if (session("type")!="admin") return $this->error("无权访问");
        if (session("cid")=="0") $res=db('doctor')->where("id",input("id"))->delete();
        else $res=db('doctor')->where("id",input("id"))->where("clinic",session("cid"))->delete();
        if (($res==1)) $this->success('删除成功','/Doctor/List');
        else $this->error('删除失败');
    }
}